<template>
  <div class="h-full">
    <n-card class="h-full shadow-sm rounded-16px">
      <n-form class="w-full" size="small" inline>
        <n-form-item label="车间:" label-placement="left" style="width: 200px">
          <n-select
            v-model:value="selectedAreas"
            clearable
            multiple
            label-field="areaname"
            value-field="areaname"
            :options="areas"
          />
        </n-form-item>
        <n-form-item label="内部订单:" label-placement="left">
          <n-input v-model:value="lotname" type="text" placeholder="模糊查询" />
        </n-form-item>
        <n-form-item label="物料类型:" label-placement="left" style="width: 200px">
          <n-select
            v-model:value="selectedMaterialType"
            clearable
            multiple
            label-field="MATERIALTYPE"
            value-field="MATERIALTYPE"
            :options="materialTypes"
          />
        </n-form-item>
        <n-form-item label="物料料号:" label-placement="left">
          <n-input v-model:value="materialName" type="text" placeholder="模糊查询" />
        </n-form-item>
        <n-form-item label="时间段:" label-placement="left">
          <n-date-picker v-model:value="range" type="datetimerange" clearable />
        </n-form-item>
        <n-form-item label="" label-placement="left">
          <n-button type="primary" :on-click="getMdcMaterialList">
            <template #icon><icon-mdi-map-search-outline /></template>
            查询
          </n-button>
        </n-form-item>
      </n-form>
      <vxe-grid v-bind="materialOptions" @cell-click="cellClickEvent"></vxe-grid>
    </n-card>
    <n-modal v-model:show="showModal">
      <n-card style="width: 1280px" title="物料履历" :bordered="false" size="huge" role="dialog" aria-modal="true">
        <vxe-grid v-bind="materialHisOptions"></vxe-grid>
      </n-card>
    </n-modal>
  </div>
</template>

<script setup lang="tsx">
import { onMounted, reactive, ref } from 'vue';
import dayjs from 'dayjs';
import type { VxeGridProps } from 'vxe-table';
import { fetchAreaList, fetchMdcMaterialHis, fetchMdcMaterialList, fetchMdcMaterialTypeList } from '@/service';

const areas = ref<Factory.Area[]>([]);
const selectedAreas = ref([]);

const materialTypes = ref<any[]>([]);
const selectedMaterialType = ref([]);

const lotname = ref('');
const materialName = ref('');
const range = ref<[number, number]>([dayjs().startOf('month').valueOf(), Date.now()]);

const showModal = ref(false);

const sumNum = (list: any[], field: string) => {
  let count = 0;
  list.forEach(item => {
    count += Number(item[field]);
  });
  return count;
};

const materialOptions = reactive<VxeGridProps>({
  border: true,
  size: 'mini',
  maxHeight: '550px',
  showFooter: true,
  align: 'center',
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'LOCATIONNAME',
      title: '车间',
      width: '160px',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'CREATETIME',
      title: '创建日期',
      sortable: true
    },
    {
      field: 'WORKORDERID',
      title: '内部订单',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'MATERIALTYPE',
      title: '物料类型',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'MATERIALNAME',
      title: '物料料号',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'LOTNO',
      title: '流水号',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'MATERIALSTOCKIN',
      title: '入库数量'
    },
    {
      field: 'MATERIALOUT',
      title: '总领用量'
    },
    {
      field: 'MATERIALRETURN',
      title: '总退回量'
    },
    {
      field: 'CURRENTMATERIALQUANTITY',
      title: '当前数量'
    }
  ],
  toolbarConfig: {
    buttons: [],
    export: true,
    print: true,
    // zoom: true,
    custom: true
  },
  data: [],
  mergeCells: [],
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return 'Σ总计';
        }
        if (
          column.field === 'MATERIALSTOCKIN' ||
          column.field === 'MATERIALOUT' ||
          column.field === 'MATERIALRETURN' ||
          column.field === 'CURRENTMATERIALQUANTITY'
        ) {
          return sumNum(data, column.property);
        }
        return '';
      })
    ];
  },
  exportConfig: {
    remote: false,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all']
  }
});

const materialHisOptions = reactive<VxeGridProps>({
  border: true,
  size: 'mini',
  showFooter: false,
  align: 'center',
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'EVENTTIME',
      title: '操作日期',
      sortable: true
    },
    {
      field: 'OPERTYPE',
      title: '操作',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'EVENTCOMMENT',
      title: '备注',
      showOverflow: true
    },
    {
      field: 'SHIPUSER',
      title: '领用/退还人',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'QUALITYQUANTITY',
      title: '领用/退还数量'
    },
    {
      field: 'CURRENTMATERIALQUANTITY',
      title: '在库数量'
    },
    {
      field: 'EVENTUSER',
      title: '操作人',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    }
  ],
  toolbarConfig: {
    buttons: [],
    export: true,
    print: true,
    // zoom: true,
    custom: true
  },
  data: [],
  mergeCells: [],
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return 'Σ总计';
        }
        if (columnIndex === 4) {
          return sumNum(data, column.property);
        }
        return '';
      })
    ];
  },
  exportConfig: {
    remote: false,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all']
  }
});

const getAreaList = async () => {
  const result = await fetchAreaList();
  if (result.data) {
    areas.value = result.data;
  }
};

const getMdcMaterialTypeList = async () => {
  const result = await fetchMdcMaterialTypeList();
  if (result.data) {
    materialTypes.value = result.data;
  }
};

const getMdcMaterialList = async () => {
  const result = await fetchMdcMaterialList(
    dayjs(range.value[0]).format('YYYYMMDDHHmmss'),
    dayjs(range.value[1]).format('YYYYMMDDHHmmss'),
    selectedAreas.value.join(','),
    materialName.value,
    selectedMaterialType.value.join(','),
    lotname.value
  );
  if (result.data) {
    materialOptions.data = result.data;
  }
};

const cellClickEvent = async ({ row }: { row: any }) => {
  const result = await fetchMdcMaterialHis(row.MATERIALNAME, row.LOTNO, row.WORKORDERID);
  if (result.data) {
    materialHisOptions.data = result.data;
  }
  showModal.value = true;
};

onMounted(async () => {
  getAreaList();
  getMdcMaterialTypeList();
});
</script>
<style scoped></style>
